package com.dotools.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Process;
import android.provider.Settings;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;

public class DevicesUtils_MIUI {
    public final static String ROM_MIUI_V5 = "V5";
    public final static String ROM_MIUI_V6 = "V6";
    public final static String ROM_MIUI_V7 = "V7";
    public final static String ROM_MIUI_V8 = "V8";
    public final static String ROM_MIUI_V9 = "V9";
    public final static String ROM_MIUI_V10 = "V10";
    public final static String ROM_MIUI_V11 = "V11";
    public final static String ROM_MIUI_V12 = "V12";
    public final static String ROM_MIUI_V12_5 = "V125";
    public final static String ROM_MIUI_V13 = "V13";
    /**
     * 是否是MIUI5
     */
    private static Boolean isV5 = null;

    public static boolean isV5() {
        if (isV5 == null) {
            isV5 = ROM_MIUI_V5.equals(getRom());
        }
        return isV5;
    }

    /**
     * 是否是MIUI6
     */
    private static Boolean isV6 = null;

    public static boolean isV6() {
        if (isV6 == null) {
            isV6 = ROM_MIUI_V6.equals(getRom());
        }
        return isV6;
    }

    /**
     * 是否是MIUI7
     */
    private static Boolean isV7 = null;

    public static boolean isV7() {
        if (isV7 == null) {
            isV7 = ROM_MIUI_V7.equals(getRom());
        }
        return isV7;
    }

    private static Boolean isV8 = null;

    public static boolean isV8() {
        if (isV8 == null) {
            isV8 = ROM_MIUI_V8.equals(getRom());
        }
        return isV8;
    }


    private static Boolean isV9 = null;

    public static boolean isV9() {
        if (isV9 == null) {
            isV9 = ROM_MIUI_V9.equals(getRom());
        }
        return isV9;
    }


    private static Boolean isV10 = null;

    public static boolean isV10() {
        if (isV10 == null) {
            isV10 = ROM_MIUI_V10.equals(getRom());
        }
        return isV10;
    }

    private static Boolean isV11 = null;

    public static boolean isV11() {
        if (isV11 == null) {
            isV11 = ROM_MIUI_V11.equals(getRom());
        }
        return isV11;
    }

    private static Boolean isV12 = null;

    public static boolean isV12() {
        if (isV12 == null) {
            isV12 = ROM_MIUI_V12.equals(getRom());
        }
        return isV12;
    }


    private static Boolean isV12_5 = null;

    public static boolean isV12_5() {
        if (isV12_5 == null) {
            isV12_5 = ROM_MIUI_V12_5.equals(getRom());
        }
        return isV12_5;
    }


    private static Boolean isV13 = null;

    public static boolean isV13() {
        if (isV13 == null) {
            isV13 = ROM_MIUI_V13.equals(getRom());
        }
        return isV13;
    }



    /**
     * 是否是小米
     */
    public static boolean isMIUI() {
        if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi") || !TextUtils.isEmpty(getRom()))
            return true;
        else
            return false;
    }

    /**
     * 获得小米版本v8 V7 V6 V5
     */
    public static String getRom() {
        return getSystemProperty("ro.miui.ui.version.name");
    }

    private static String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            java.lang.Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
        return line;
    }


    /**
     * 打开MIUI权限管理界面
     *
     * @param context
     */
    public static void openMiuiPermissionsActivity(Context context) {
        openMiuiPermissionsActivity(context, 99);
    }

    public static void openMiuiPermissionsActivity(Context context, int resultCode) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        String SCHEME = "package";
        if (DevicesUtils_MIUI.isV5()) {
            intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts(SCHEME, context.getPackageName(), null);
            intent.setData(uri);
            context.startActivity(intent);
            return;
        } else if (DevicesUtils_MIUI.isV6() || DevicesUtils_MIUI.isV7()) {
            intent.setClassName("com.miui.securitycenter",
                    "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            intent.putExtra("extra_pkgname", context.getPackageName());
        } else if (DevicesUtils_MIUI.isV8()
                || DevicesUtils_MIUI.isV9()
                || DevicesUtils_MIUI.isV10()
                || DevicesUtils_MIUI.isV11()
                ||DevicesUtils_MIUI.isV12()
                ||DevicesUtils_MIUI.isV12_5()
                ||DevicesUtils_MIUI.isV13()) {
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            intent.putExtra("extra_pkgname", context.getPackageName());
        }else {
            //打开该应用详情
            if (Build.VERSION.SDK_INT >= 9) {
                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                intent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                intent.setAction(Intent.ACTION_VIEW);
                intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (isIntentAvailable(context, intent)) {
            if (context instanceof Activity) {
                Activity a = (Activity) context;
                a.startActivityForResult(intent, resultCode);
            } else {
                context.startActivity(intent);
            }
        }
    }


    /**
     * 检查后台弹出界面权限
     */
    public static boolean checkBackstagePop(Context context) {
        AppOpsManager ops = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        try {
            int op = 10021;
            Method method = ops.getClass().getMethod("checkOpNoThrow", new Class[]{int.class, int.class, String.class});
            Integer result = (Integer) method.invoke(ops, op, Process.myUid(), context.getPackageName());
            return result == AppOpsManager.MODE_ALLOWED;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 打开MIUI开发者选项界面(MIUI v5, v6)
     *
     * @param context
     */
    public static void openMiuiDeveloperActivity(Context context) {
        Intent intent = new Intent(
                "com.android.settings.APPLICATION_DEVELOPMENT_SETTINGS");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.setClassName("com.android.settings",
                "com.android.settings.Settings$DevelopmentSettingsActivity");
        intent.putExtra("extra_pkgname", context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (isIntentAvailable(context, intent)) {
            context.startActivity(intent);
        }
    }


    /**
     * 判断是否有可以接受的Activity
     *
     * @param context
     * @return
     */
    @SuppressLint("WrongConstant")
    public static boolean isIntentAvailable(Context context, Intent intent) {
        if (intent == null)
            return false;
        return context.getPackageManager()
                .queryIntentActivities(intent, PackageManager.GET_ACTIVITIES)
                .size() > 0;
    }

    /**
     * 判断是否拥有悬浮窗的权限
     *
     * @param context
     * @return
     */
    public static boolean hasFloatWindowPermission(Context context) {
        if (needFloatWindowPermission()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                return checkOp(Utilities.getApplicationContext()) == 1;
            }
            ApplicationInfo applicationInfo;
            try {
                applicationInfo = context.getPackageManager().getApplicationInfo(
                        context.getPackageName(), 0);
                return ((applicationInfo.flags & 1 << 27) == 134217728);
            } catch (NameNotFoundException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    @SuppressLint("WrongConstant")
    public static int checkOp(Context context) {
        try {
            Object localObject = context.getSystemService("appops");
            Class localClass = localObject.getClass();
            Class[] arrayOfClass = new Class[3];
            arrayOfClass[0] = Integer.TYPE;
            arrayOfClass[1] = Integer.TYPE;
            arrayOfClass[2] = String.class;
            Method localMethod = localClass.getMethod("checkOp", arrayOfClass);
            Object[] arrayOfObject = new Object[3];
            arrayOfObject[0] = Integer.valueOf(24);
            arrayOfObject[1] = Integer.valueOf(Binder.getCallingUid());
            arrayOfObject[2] = context.getPackageName();
            int j = ((Integer) localMethod.invoke(localObject, arrayOfObject)).intValue();
            if (j == 0)
                return 1;
            return 0;
        } catch (Throwable localThrowable2) {
            return -1;
        }
    }

    /**
     * 针对小米是否需要悬浮窗
     *
     * @return
     */
    public static boolean needFloatWindowPermission() {
        return DevicesUtils_MIUI.isMIUI();
    }


    /**
     * \
     * 打开小米自启动
     *
     * @param context
     */
    public static void openAutoMIUISetting(Context context) {
        Intent intent = new Intent();
        ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
        intent.setComponent(componentName);
        if (isIntentAvailable(context, intent)) {
            if (context instanceof Activity) {
                Activity a = (Activity) context;
                a.startActivity(intent);
            } else {
                context.startActivity(intent);
            }
        }
    }

    /****
     * 跳转小米市场详细APP页面
     * 小米手机会自动拦截market协议，跳转到自己的市场，非小米手机 此方法不可用
     * @param act   必须是ACTIVITY
     * @param pkg  APP包名
     */
    public static void jump2XiaomiMarket(Activity act, String pkg) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + pkg));
        act.startActivity(intent);
    }
}
